<template>
  <div class="settings-page">
    <h2 class="title">设置</h2>

    <el-divider />

    <!-- 修改头像 - 整个条目可点击 -->
    <div class="setting-item avatar-item" @click="triggerFileInput">
      <span>修改头像</span>
      <div class="edit-box">
        <el-avatar :size="60" :src="user.avatar" class="avatar-preview" />
        <el-icon><ArrowRight /></el-icon>
        <input 
          type="file" 
          ref="fileInput" 
          style="display: none" 
          accept="image/jpeg,image/png,image/gif" 
          @change="handleFileChange"
        >
      </div>
    </div>

    <!-- 修改密码 -->
    <div class="setting-item" @click="goChangePassword">
      <span>修改密码</span>
      <el-icon><ArrowRight /></el-icon>
    </div>

    <!-- 修改绑定手机号 -->
    <div class="setting-item phone-item">
      <span>修改绑定手机号</span>
      <div class="edit-box">
        <el-input v-model="newPhone" placeholder="请输入新手机号" class="input-small" />
        <el-button type="primary" size="small" @click="updatePhone">修改</el-button>
      </div>
    </div>

    <!-- 修改绑定邮箱 -->
    <div class="setting-item email-item">
      <span>修改绑定邮箱</span>
      <div class="edit-box">
        <el-input v-model="newEmail" placeholder="请输入新邮箱" class="input-small" />
        <el-button type="primary" size="small" @click="updateEmail">修改</el-button>
      </div>
    </div>

    <!-- 其他设置项 -->
    <div class="setting-item" v-for="item in otherSettings" :key="item" @click="handleSettingClick(item)">
      <span>{{ item }}</span>
      <el-icon><ArrowRight /></el-icon>
    </div>

    <el-divider />

    <!-- 退出登录 -->
    <div class="setting-item logout-item" @click="handleLogout">
      <span>退出登录</span>
      <el-icon><SwitchButton /></el-icon>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowRight, SwitchButton } from '@element-plus/icons-vue'
import apiClient from '../../utils/request'
import {authHandler} from '../../utils/authUtils'
const router = useRouter()
const fileInput = ref(null)

// 用户数据
const user = ref({
  avatar: localStorage.getItem('user_avatar') || '',
  phone: localStorage.getItem('user_phone') || '',
  email: localStorage.getItem('user_email') || ''
})

// 修改内容
const newPhone = ref('')
const newEmail = ref('')

// 触发文件选择
const triggerFileInput = (e) => {
  // 阻止事件冒泡，避免多次触发
  e.stopPropagation()
  fileInput.value.click()
}

// 处理头像上传
const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  const validTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!validTypes.includes(file.type)) {
    ElMessage.error('只支持 JPG/PNG/GIF 格式的图片')
    return
  }

  // 验证文件大小 (2MB)
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过 2MB')
    return
  }

  try {
    const token = localStorage.getItem('access_token')
    if (!token) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    // 创建FormData对象
    const formData = new FormData()
    formData.append('avatar', file)

    // 发送上传请求
    const response = await apiClient.post('/api/users/upload-avatar/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      }
    })

    // 处理成功响应
    if (response.data?.avatar_url) {
      user.value.avatar = response.data.avatar_url
      localStorage.setItem('user_avatar', response.data.avatar_url)
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error('无效的响应格式')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    if (error.response) {
      switch (error.response.status) {
        case 400:
          ElMessage.error(error.response.data?.message || '请求参数错误')
          break
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          handleLogout()
          break
        case 413:
          ElMessage.error('文件大小超过限制')
          break
        case 415:
          ElMessage.error('不支持的图片格式')
          break
        default:
          ElMessage.error(error.response.data?.message || '上传失败')
      }
    } else {
      ElMessage.error('网络错误，请检查连接')
    }
  } finally {
    event.target.value = ''
  }
}

// 修改手机号
const updatePhone = async () => {
  if (!newPhone.value) {
    ElMessage.warning('请输入新手机号')
    return
  }
  
  // 手机号验证
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(newPhone.value)) {
    ElMessage.error('请输入有效的手机号')
    return
  }

  try {
    const token = localStorage.getItem('access_token')
    if (!token) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    const response = await apiClient.post('/api/users/reset-phone-or-email/', {
      new_phone: newPhone.value
    })

    if (response.status === 200) {
      user.value.phone = newPhone.value
      localStorage.setItem('user_phone', newPhone.value)
      newPhone.value = ''
      ElMessage.success('手机号更新成功')
    }
  } catch (error) {
    console.error('修改手机号失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data?.message || '修改手机号失败')
    } else {
      ElMessage.error('网络错误，请检查连接')
    }
  }
}

// 修改邮箱
const updateEmail = async () => {
  if (!newEmail.value) {
    ElMessage.warning('请输入新邮箱')
    return
  }
  
  // 邮箱验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(newEmail.value)) {
    ElMessage.error('请输入有效的邮箱地址')
    return
  }

  try {
    const token = localStorage.getItem('access_token')
    if (!token) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    const response = await apiClient.post('/api/users/reset-phone-or-email/', {
      new_email: newEmail.value
    })

    if (response.status === 200) {
      user.value.email = newEmail.value
      localStorage.setItem('user_email', newEmail.value)
      newEmail.value = ''
      ElMessage.success('邮箱更新成功')
    }
  } catch (error) {
    console.error('修改邮箱失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data?.message || '修改邮箱失败')
    } else {
      ElMessage.error('网络错误，请检查连接')
    }
  }
}
// 修改密码
const goChangePassword = () => {
  router.push('/phone-reset-password')
}

const handleSettingClick = (item) => {
  ElMessage.info(`${item}功能开发中`)
}
// 退出登录
const handleLogout = async () => {
  try {
    const refreshToken = localStorage.getItem('refresh_token')
    if (refreshToken) {
      await apiClient.post('/api/users/Logout/', {
        refresh_token: refreshToken
      })
    }
  } catch (error) {
    console.error('退出登录失败:', error)
  } finally {
    authHandler.clearAuthInfo()
    
    // 触发全局事件
    window.dispatchEvent(new CustomEvent('login-status-changed', {
      detail: { isLoggedIn: false }
    }))
    
    router.push('/login')
  }
}

const otherSettings = ['隐私设置', '通知设置', '黑名单管理']

// 初始化检查登录状态
onMounted(() => {
  if (!localStorage.getItem('access_token')) {
    router.push('/login')
  }
})
</script>

<style scoped>
.settings-page {
  padding: 20px;
  background: #fff;
  min-height: 100vh;
  max-width: 800px;
  margin: 0 auto;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 12px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 16px;
  color: #333;
  transition: background-color 0.2s;
  cursor: pointer;
}

.setting-item:hover {
  background-color: #f9f9f9;
}

.avatar-item {
  align-items: center;
}

.edit-box {
  display: flex;
  align-items: center;
  gap: 12px;
}

.input-small {
  width: 200px;
}

.avatar-preview {
  transition: transform 0.3s;
}

.avatar-preview:hover {
  transform: scale(1.05);
}

.logout-item {
  color: #f56c6c;
  justify-content: center;
  margin-top: 10px;
}

.logout-item:hover {
  background-color: #fef0f0;
}

.logout-item .el-icon {
  color: #f56c6c;
  margin-left: 8px;
}

.el-divider {
  margin: 20px 0;
}

.el-icon {
  color: #999;
}
</style>